package com.uyaer.wheel.res
{
	import com.uyaer.wheel.common.Config;
	import com.uyaer.wheel.utils.HashMap;
	import com.uyaer.wheel.utils.Utils;
	
	import starling.textures.Texture;
	import starling.textures.TextureAtlas;
	import starling.utils.AssetManager;

	public class ResManager extends AssetManager
	{
		private static var _assets:ResManager;
		
		public function ResManager(){
			super();
			
		}
		
		public static function get me():ResManager{
			return _assets ||= new ResManager();
		}
		
		private var loadedUrlMap:HashMap = new HashMap();
		
		/**
		 *获得需要加载的资源 
		 * @param uri = ResURI.home
		 * @return 
		 * 
		 */		
		public function getResURI(uri:Array):Array{
			var arr:Array = new Array();
			for each (var e:String in uri){
				if(!loadedUrlMap.hasKey(Utils.getName(e))){
					arr.push(Config.textureSource+e);
				}
			}
			return arr;
		}
		
		/**
		 *销毁素材 
		 * @param arr
		 * 
		 */		
		public function destoryURI(uris:Array):void{
			var arr:Array = new Array();
			for each (var e:String in uris){
				arr.push(e);
			}
			
			while(arr.length>0){
				var uri:String = arr.pop();
				var name:String = Utils.getName(uri);
				var ext:String = Utils.getExt(uri);
				var index:int = checkHaspair(name,ext,arr); //检查配对的位置
				loadedUrlMap.remove(name);
				if(index < 0){ //无配对
					this.removeTexture(name,true);
				}else{
					this.removeTextureAtlas(name,true);
					arr.splice(index,1);
				}
			}
		}
		
		/**
		 *检查是否有配对的情况 
		 * @param name
		 * @param ext
		 * @param arr
		 * @return 
		 * 
		 */		
		private function checkHaspair(name:String,ext:String,arr:Array):int{
			for(var i:int = 0 ;i < arr.length ; i ++){
				var uri:String =  arr[i];
				if(name == Utils.getName(uri) && ext != Utils.getExt(uri)){
					return i;
				}
			}
			return -1;
		}
		
		override public function addTextureAtlas(name:String, atlas:TextureAtlas):void{
			super.addTextureAtlas(name, atlas);
			if(!loadedUrlMap.hasKey(name)){
				loadedUrlMap.put(name,name);
			}else{
				throw "资源命名不要重名";
			}
		}
		
		override public function addTexture(name:String, texture:Texture):void{
			super.addTexture(name, texture);
			if(!loadedUrlMap.hasKey(name)){
				loadedUrlMap.put(name,name);
			}else{
				throw "资源命名不要重名";
			}
		}
	}
}